<?php

namespace addons\kzvote\controller;

use addons\kzvote\library\WechatService;
use addons\kzvote\model\UserModel;
use app\common\library\Token;
use app\common\model\kzvote\Store;
use app\common\model\kzvote\Vote;
use fast\Random;
use think\Validate;

/**
 * 用户接口
 */
class User extends Base
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';
    protected $visibleFields = ['id', 'avatar', 'nickname', 'mobile', 'status', 'username'];

    /**
     * 授权登录
     * @ApiMethod   (POST)
     * @param string $code 授权code
     * @param string $userInfo 授权后拿到的用户信息
     */
    public function login()
    {
        $code = input('code/s', '');
        if (!$code) {
            $this->error('缺少小程序参数code');
        }

        $service = new WechatService();
        $oauth_user = $service->miniLogin($code);
        if (!isset($oauth_user['openid'])) {
            $this->error('获取小程序用户信息失败');
        }

        //$openid = UserModel::oauth($oauth_user);
        $openid = UserModel::thirdOauth($oauth_user);
        if (empty($openid)) {
            //$user = UserModel::fastRegister($oauth_user,'wxapp');
            $isBind = \addons\third\library\Service::isBindThird("wechat", $oauth_user['openid'], "miniapp", $oauth_user['unionid']);
            if ($this->auth->isLogin()) {
                if ($isBind) {
                    $this->error("已经绑定其它账号，无法进行绑定");
                }
            }
            \addons\third\library\Service::connect("wechat", $oauth_user);
        }else{
            if (!$openid['openid']){
                $openid->openid = $oauth_user['openid'];
                $openid->save();
            }
            $this->auth->direct($openid['user_id']);
        }
        $user = $this->auth->getUser()->visible($this->visibleFields)->toArray();
        if (!$user){
            $this->error('注册用户失败');
        }

        // 清除之前的token
//        Token::clear($user->id);

        // 直接登录
        //$this->auth->direct($user->id);

        //$user = $this->auth->getUser()->visible($this->visibleFields)->toArray();
        if(strpos($user['avatar'],'data:image') !== false){
            $user['avatar'] = '';
        }

        $this->success('', [
            'token' => $this->auth->getToken(),
            'user' => $user
        ]);
    }

    /**
     * 用户信息
     */
    public function detail()
    {
        $user = $this->auth->getUser()->visible($this->visibleFields)->toArray();
        if(strpos($user['avatar'],'data:image') !== false){
            $user['avatar'] = '';
        }
        //我创建的
        $vote['create'] = Vote::where('user_id',$user['id'])->where('status', '<', '30')->count();
        //我报名的
        $vote['joins'] = (new Vote)->alias('vote')
            ->join('kzvote_log log', 'log.vote_id = vote.id')
            ->distinct(true)
            ->where(['log.user_id' => $user['id']])
            ->where('vote.status', '<', '30')
            ->group('vote.id')
            ->count();
        //3.我报名的
        $vote['apply'] = (new Vote)->alias('vote')
            ->join('kzvote_person p', 'p.vote_id = vote.id')
            ->where('vote.status', '<', '30')
            ->where(['p.user_id' => $user['id']])
            ->group('p.user_id')
            ->count();
        $this->success('', ['user'=>$user,'vote'=>$vote]);
    }

    /**
     * 获取微信绑定的手机号码
     */
    public function getPhone()
    {
        $code = $this->request->post('code','','trim');
        $iv = $this->request->post('iikv','','trim');
        $encryptedData = $this->request->post('data','','trim');
        if (!$code) {
            $this->error('缺少小程序参数code');
        }
        if (!$iv) {
            $this->error('缺少小程序参数iv');
        }
        if (!$encryptedData) {
            $this->error('缺少小程序参数encryptedData');
        }

        $service = new WechatService();
        $wechat = $service->miniLogin($code);
        $session_key = $wechat['session_key'] ?? '';

        if (!$session_key) {
            $this->error('获取手机号失败，请稍后重试');
        }

        $data = $service->decryptedData($session_key, $iv, $encryptedData);
        if (isset($data['phoneNumber'])) {
            $user = $this->auth->getUser();
            if(strpos($user['avatar'],'data:image') !== false){
                $user->avatar = '';
            }
            $user->mobile = $data['phoneNumber'];
            $user->save();
            $this->success('绑定成功',['user'=>$user->visible($this->visibleFields)->toArray(),'mobile'=>$user->mobile]);
        } else {
            $this->error('获取手机号失败，请稍后重试');
        }
    }

    /**
     * 保存个人信息
     */
    public function save()
    {
        $update_fields = ['avatar', 'nickname', 'mobile', 'gender', 'birthday'];
        $data = ['updatetime' => time()];
        foreach ($update_fields as $field) {
            if ($value = input("{$field}/s", '')) {
                $data[$field] = $value;
            }
        }

        $user = $this->auth->getUser();
        if ($user->save($data)) {
            $user = $this->auth->getUser()->visible($this->visibleFields)->toArray();
            if(strpos($user['avatar'],'data:image') !== false){
                $user['avatar'] = '';
            }
            $this->success('',compact('user'));
        }

        $this->error('保存失败，请重试');
    }

    /*
     * 用户后台信息
     */
    public function store(){
        $user = $this->auth->getUser();
        $username = Store::where('user_id',$user['id'])->value('username');
        $this->success('',$username);
    }

    /**
     * 注册
     */
    public function register()
    {
        $user = $this->auth->getUser();
        $username = Store::where('user_id',$user['id'])->value('username');
        if($username){
            $this->error('您已经注册过了');
        }
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $rule = [
            'username'  => 'require|length:3,30',
            'password'  => 'require|length:6,30',
        ];

        $msg = [
            'username.require' => '用户名不能为空',
            'username.length'  => '用户名必须3-30个字符',
            'password.require' => '密码不能为空',
            'password.length'  => '密码必须6-30个字符',
        ];
        $data = [
            'username'  => $username,
            'password'  => $password,
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $salt = Random::alnum();
        $res = Store::create([
            'user_id' => $user['id'],
            'username' => $username,
            'salt' => $salt,
            'password' => md5(md5($password) . $salt)
        ]);
        if ($res) {
            $this->success('注册成功',$username);
        } else {
            $this->error('注册失败');
        }
    }

    //重置密码
    public function resetPwd(){
        $user = $this->auth->getUser();
        $store = Store::where('user_id',$user['id'])->find();
        if(!$store){
            $this->error('您还没有注册');
        }
        $new_password = $this->request->post('new_password');
        $rule = [
            'new_password'  => 'require|length:6,30',
        ];

        $msg = [
            'new_password.require' => '新密码不能为空',
            'new_password.length'  => '新密码必须6-30个字符',
        ];
        $data = [
            'new_password'  => $new_password,
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $salt = Random::alnum();
        $new_password = md5(md5($new_password) . $salt);
        $res = Store::where('user_id',$user['id'])->update(['password'=>$new_password,'salt'=>$salt]);
        if ($res) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }
}
